package org.shop.controller.upload;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.shop.dao.UserDao;
import org.shop.dao.impl.UserDaoImpl;
import org.shop.entity.User;
import org.shop.util.FileUploadUtil;

/**
 * 文件上传 - 封装上传工具 - 实现用户头像的修改
 * 
 * @author zqx
 *
 */
@WebServlet("/admin/upload3.do")
@MultipartConfig
public class Upload3Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1.获取非文件域的数据，仍然使用之前的getParameter和getParameterValues方法获取
		Part part = req.getPart("head") ;
		String path = this.getServletContext().getRealPath("/file/head") ;
		
		// 2.实例化文件上传工具对象
		FileUploadUtil fileUploadUtil = new FileUploadUtil(1*1024*1024,"jpeg,jpg,png,gif");
		
		// 3.上传文件
		String filename = fileUploadUtil.upload(part, path) ;
		
		
		// 4.实例化DAO对象，修改用户头像文件名
		UserDao userDao = new UserDaoImpl();
		
		// 5.从会话中，获取登录用户
		User user = (User)req.getSession().getAttribute("user") ;
		
		// 6.修改头像成功后，必须重新登录，从而能重新查询修改的头像
		int r = userDao.updateUser(user.getId(), filename) ;
		if(r==1) {
			resp.sendRedirect("login.jsp") ;
		}
	}
}





